var express = require("express");
var router = express.Router();
var moment = require("moment");
const { Op } = require("sequelize");
const Product = require("../db/model/productModel");
const { check } = require("express-validator");
const { checkParam } = require("../utils/checkUtils");
const { success } = require("../utils/result");

/**
 * @api {POST} /product/queryList 商品列表
 * @apiDescription 商品列表
 * @apiName queryList
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} page=1   页码
 * @apiBody {Number} limit=10   每页条数
 * @apiBody {String} product_name=iphone   商品名称
 * @apiBody {Number} status=1   商品状态
 * @apiParamExample {json} Request-Example:
 *     {
 *        "page": 1,
 *        "limit": "10",
 *        "status": 1
 *        "product_name", "xxx"
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */
router.post("/product/queryList", async function (req, res) {
  const { page, limit, status, product_name, is_hot } = req.body;
  if (!page) {
    return res.send({ code: 500, message: "缺少page参数" });
  }
  if (!limit) {
    return res.send({ code: 500, message: "缺少limit参数" });
  }
  let where = {};
  if (product_name) {
    where["product_name"] = {
      [Op.like]: "%" + product_name + "%",
    };
  }
  if (status === 0 || status === 1) {
    where["status"] = status;
  }
  if (is_hot === 0 || is_hot === 1) {
    where["is_hot"] = is_hot;
  }
  let offset = (page - 1) * limit;
  try {
    const result = await Product.findAndCountAll({
      limit,
      offset,
      where,
      order: [["created_time", "DESC"]],
    });
    return res.json({ code: 200, message: "success", data: result });
  } catch (error) {
    console.log(error);
    return res.json({ code: -1, message: "商品查询失败" });
  }
});

/**
 * @api {POST} /product/add 商品添加
 * @apiDescription 商品添加
 * @apiName add
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {String} product_name='商品名称'   商品名称
 * @apiBody {String} desc='商品描述（标题下方小文字）' 商品描述（标题下方小文字）
 * @apiBody {Number} cate_id=1   分类id
 * @apiBody {Number} sale_price=1   商品销售价格
 * @apiBody {Number} original_price=1   商品原价
 * @apiBody {String} head_img=''   商品头图（商品列表展示图）
 * @apiBody {String} carousel_img=''   商品轮播图（详情下面滚动图）用逗号分隔
 * @apiBody {String} detail='xxxx内容'   商品详情（保存为HTML）
 * @apiBody {Number} status=1   状态（0 下架 1 上架）
 * @apiBody {Number} stock=1  库存
 * @apiBody {Number} is_hot 是否热门 (0 否 1 是))
 * @apiParamExample {json} Request-Example:
 *     {
 *        "product_name": 1,
 *        "desc": "10",
 *        "cate_id": 1,
 *        "sale_price": 1,
 *        "original_price": 1,
 *        "head_img": 1,
 *        "carousel_img": 1,
 *        "detail": 1,
 *        "status": 1,
 *        "stock": 1,
 *        "is_hot": 1
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */

router.post("/product/add", async function (req, res) {
  try {
    const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    let {
      product_name,
      desc,
      cate_id,
      sale_price,
      original_price,
      head_img,
      carousel_img,
      detail,
      status,
      stock,
      is_hot,
    } = req.body;
    if (!product_name) {
      return res.send({ code: 500, msg: "缺少product_name参数" });
    }
    if (!desc) {
      return res.send({ code: 500, msg: "缺少desc参数" });
    }
    if (!cate_id) {
      return res.send({ code: 500, msg: "缺少cate_id参数" });
    }
    if (!sale_price) {
      return res.send({ code: 500, msg: "缺少sale_price参数" });
    }
    if (!original_price) {
      return res.send({ code: 500, msg: "缺少original_price参数" });
    }
    if (!head_img) {
      return res.send({ code: 500, msg: "缺少head_img参数" });
    }
    if (!carousel_img) {
      return res.send({ code: 500, msg: "缺少carousel_img参数" });
    }
    if (carousel_img && carousel_img.split(",").length < 3) {
      return res.send({ code: 500, msg: "商品轮播图必须大于等于三张" });
    }
    if (!detail) {
      return res.send({ code: 500, msg: "缺少detail参数" });
    }
    let shelvesStatus = 1; // 默认上架
    if (status === 0 || status === 1) {
      shelvesStatus = status;
    }
    // 是否热门
    if (is_hot !== 0 && is_hot !== 1) {
      is_hot = 0;
    }

    const result = await Product.create({
      product_name,
      desc,
      cate_id,
      sale_price,
      original_price,
      head_img,
      carousel_img,
      detail,
      create_time: time,
      updated_time: time,
      status: shelvesStatus,
      stock,
      is_hot,
    });
    console.log("status", status);
    console.log("shelvesStatus", shelvesStatus);
    console.log("添加商品成功", result);
    return res.json({ code: 200, message: "创建成功" });
  } catch (error) {
    console.log(error);
    return res.json({
      code: 500,
      message: "创建失败:" + err,
    });
  }
});

/**
 * @api {POST} /product/edit 商品编辑
 * @apiDescription 商品编辑
 * @apiName edit
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1  主键
 * @apiBody {String} product_name='商品名称'   商品名称
 * @apiBody {String} desc='商品描述（标题下方小文字）' 商品描述（标题下方小文字）
 * @apiBody {Number} cate_id=1   分类id
 * @apiBody {Number} sale_price=1   商品销售价格
 * @apiBody {Number} original_price=1   商品原价
 * @apiBody {String} head_img=''   商品头图（商品列表展示图）
 * @apiBody {String} carousel_img=''   商品轮播图（详情下面滚动图）用逗号分隔
 * @apiBody {String} detail='xxxx内容'   商品详情（保存为HTML）
 * @apiBody {Number} status=1   状态（0 下架 1 上架）
 * @apiBody {Number} stock=1   库存
 * @apiBody {Number} is_hot=1  是否热门
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "product_name": 1,
 *        "desc": "10",
 *        "cate_id": 1,
 *        "sale_price": 1,
 *        "original_price": 1,
 *        "head_img": 1,
 *        "carousel_img": 1,
 *        "detail": 1,
 *        "status": 1,
 *        "stock": 1,
 *        "is_hot": 1,
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */

router.post("/product/edit", async function (req, res) {
  try {
    const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    const {
      id,
      product_name,
      desc,
      cate_id,
      sale_price,
      original_price,
      head_img,
      carousel_img,
      detail,
      status,
      stock,
      is_hot,
    } = req.body;
    if (!product_name) {
      return res.send({ code: 500, msg: "缺少product_name参数" });
    }
    if (!desc) {
      return res.send({ code: 500, msg: "缺少desc参数" });
    }
    if (!cate_id) {
      return res.send({ code: 500, msg: "缺少cate_id参数" });
    }
    if (!sale_price) {
      return res.send({ code: 500, msg: "缺少sale_price参数" });
    }
    if (!original_price) {
      return res.send({ code: 500, msg: "缺少original_price参数" });
    }
    if (!head_img) {
      return res.send({ code: 500, msg: "缺少head_img参数" });
    }
    if (!carousel_img) {
      return res.send({ code: 500, msg: "缺少carousel_img参数" });
    }
    if (carousel_img && carousel_img.split(",").length < 3) {
      return res.send({ code: 500, msg: "商品轮播图必须大于等于三张" });
    }
    if (!detail) {
      return res.send({ code: 500, msg: "缺少detail参数" });
    }
    let shelvesStatus = 1; // 默认上架
    if (status === 0 || status === 1) {
      shelvesStatus = status;
    }

    // 查询原商品信息
    let product = await Product.findByPk(id);
    let version = product.version;
    let productMode = {
      product_name,
      desc,
      cate_id,
      sale_price,
      original_price,
      head_img,
      carousel_img,
      detail,
      create_time: time,
      updated_time: time,
      stock,
      version: version + 1,
    };

    if (status === 0 || status === 1) {
      productMode["status"] = status;
    }

    if (is_hot == 0 || is_hot == 1) {
      productMode["is_hot"] = is_hot;
    }

    const result = await Product.update(
      { ...productMode },
      { where: { id, version } }
    );
    console.log("编辑商品结束:", result);
    if (result && result.length > 0 && result[0] > 0) {
      return res.json({ code: 200, message: "更新成功" });
    }
    return res.json({ code: 500, message: "更新失败,请重试!" });
  } catch (error) {
    console.log(error);
    return res.json({
      code: 500,
      message: "更新失败:" + err,
    });
  }
});

/**
 * @api {POST} /product/updateStatus 商品上下架
 * @apiDescription 商品上下架
 * @apiName updateStatus
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiBody {Number} status=1   状态（0 下架 1 上架）
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "status": 1
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */
router.post(
  "/product/updateStatus",
  check("id").not().isEmpty(),
  check("status").not().isEmpty(),
  async function (req, res) {
    checkParam(req);
    const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    const result = await Product.update(
      {
        updated_time: time,
        status: req.body.status,
      },
      { where: { id: req.body.id } }
    );
    return res.json(success());
  }
);

/**
 * @api {POST} /product/updateIsHot 商品热门推荐
 * @apiDescription 商品上下架
 * @apiName updateIsHot
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiBody {Number} is_hot=1   状态（0 否 1 是）
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *        "is_hot": 1
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */
router.post(
  "/product/updateIsHot",
  check("id").not().isEmpty(),
  check("is_hot").not().isEmpty(),
  async function (req, res) {
    checkParam(req);
    const time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
    const result = await Product.update(
      {
        updated_time: time,
        is_hot: req.body.is_hot,
      },
      { where: { id: req.body.id } }
    );
    return res.json(success());
  }
);

/**
 * @api {POST} /product/del 删除
 * @apiDescription 删除
 * @apiName del
 * @apiHeader {String} authorization 用户token,格式：Bearer xxxx
 * @apiBody {Number} id=1   主键id
 * @apiParamExample {json} Request-Example:
 *     {
 *        "id": 1,
 *     }
 * @apiGroup Product
 * @apiVersion 1.0.0
 */
router.post(
  "/product/del",
  check("id").not().isEmpty(),
  async function (req, res) {
    checkParam(req);
    await Product.destroy({ where: { id: req.body.id } });
    return res.json(success());
  }
);

module.exports = router;
